<!-- 短信登录 - smsLogin  -->
<template>
  <view>
    <!-- 标题栏 -->
    <view class="head-box ss-m-b-60">
      <view class="ss-flex ss-m-b-20">
        <view class="head-title head-title-line head-title-animation"
          >手机号登录</view
        >
      </view>
    </view>

    <!-- 表单项 -->
    <uni-forms
      ref="smsLoginRef"
      v-model="state.model"
      :rules="state.rules"
      validateTrigger="bind"
      labelWidth="140"
      labelAlign="center"
    >
      <uni-forms-item name="mobile" label="手机号">
        <uni-easyinput
          placeholder="请输入手机号"
          v-model="state.model.mobile"
          :inputBorder="false"
          type="number"
        >
          <template v-slot:right>
            <button
              class="ss-reset-button login-btn-start"
              @tap="smsLoginSubmit"
            >
              登录
            </button>
          </template>
        </uni-easyinput>
      </uni-forms-item>
    </uni-forms>
  </view>
</template>

<script setup>
import { reactive, ref, unref } from "vue";
import sheep from "@/sheep";
import { mobile } from "@/sheep/validate/form";
import { closeAuthModal } from "@/sheep/hooks/useModal";
import { onLoad } from "@dcloudio/uni-app";

const smsLoginRef = ref(null);

const props = defineProps({
  agreeStatus: {
    type: Boolean,
    default: false,
  },
});

// 数据
const state = reactive({
  model: {
    mobile: "", // 手机号
  },
  rules: {
    mobile,
  },
});

// 手机号登录
async function smsLoginSubmit() {
  const validate = await unref(smsLoginRef)
    .validate()
    .catch((error) => {
      console.log("error: ", error);
    });
  if (!validate) return;

  if (!props.agreeStatus) {
    sheep.$helper.toast("请勾选同意");
    return;
  }

  // 调用accountLogin接口
  const params = {
    mobile: state.model.mobile,
  };

  sheep.$api.user
    .accountLogin(params)
    .then((response) => {
      sheep.$helper.toast("登录成功");
      closeAuthModal();

      // 登录成功后刷新当前页
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];

      // 刷新当前页
      if (currentPage && currentPage.onShow) {
        currentPage.onShow();
      }
      // 或者使用页面刷新方法
      if (currentPage && currentPage.$vm && currentPage.$vm.onShow) {
        currentPage.$vm.onShow();
      }

      // 如果当前页有刷新数据的方法，也可以调用
      if (currentPage && currentPage.$vm && currentPage.$vm.refreshData) {
        currentPage.$vm.refreshData();
      }
    })
    .catch((err) => {
      console.error("登录失败", err);
      console.log(err);
      console.log(params);
      sheep.$helper.toast("登录失败");
    });
}
</script>

<style lang="scss" scoped>
@import "../index.scss";
</style>
